package com.example.sharingjdbc4digiwin.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.example.sharingjdbc4digiwin.properties.ShardingJdbcDatasourceProperties;
import com.example.sharingjdbc4digiwin.properties.ShardingJdbcDruidProperties;
import io.shardingsphere.api.config.rule.ShardingRuleConfiguration;
import io.shardingsphere.api.config.rule.TableRuleConfiguration;
import io.shardingsphere.api.config.strategy.StandardShardingStrategyConfiguration;
import io.shardingsphere.shardingjdbc.api.ShardingDataSourceFactory;
import lombok.extern.slf4j.Slf4j;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Properties;

/**
 * @author： ygl
 * @date： 2019/06/22
 * @Description：
 */
@Slf4j
public class ShardingJdbcConfig_back {

    @Autowired
    private Environment environment;

    @Autowired
    private ShardingJdbcDatasourceProperties shardingJdbcDatasourceProperties;

    @Bean
    public DruidDataSource dataSourceOne() throws SQLException {
        ShardingJdbcDruidProperties one = shardingJdbcDatasourceProperties.getOne();
        return buildDruidDataSource(one);
    }

    @Bean
    public DruidDataSource dataSourceTwo() throws SQLException {
        ShardingJdbcDruidProperties two = shardingJdbcDatasourceProperties.getTwo();
        return buildDruidDataSource(two);
    }

    private DruidDataSource buildDruidDataSource(ShardingJdbcDruidProperties druidProperties){
        DruidDataSource datasource = new DruidDataSource();
        datasource.setUrl(druidProperties.getUrl());
        datasource.setUsername(druidProperties.getUsername());
        datasource.setPassword(druidProperties.getPassword());
        datasource.setDriverClassName(druidProperties.getDriverClassName());
        datasource.setInitialSize(druidProperties.getInitialSize());
        datasource.setMinIdle(druidProperties.getMinIdle());
        datasource.setMaxActive(druidProperties.getMaxActive());
        datasource.setMaxWait(druidProperties.getMaxWait());
        datasource.setTimeBetweenEvictionRunsMillis(druidProperties.getTimeBetweenEvictionRunsMillis());
        datasource.setMinEvictableIdleTimeMillis(druidProperties.getMinEvictableIdleTimeMillis());
        datasource.setMaxEvictableIdleTimeMillis(druidProperties.getMaxEvictableIdleTimeMillis());
        datasource.setValidationQuery(druidProperties.getValidationQuery());
        datasource.setTestWhileIdle(druidProperties.isTestWhileIdle());
        datasource.setTestOnBorrow(druidProperties.isTestOnBorrow());
        datasource.setTestOnReturn(druidProperties.isTestOnReturn());
        datasource.setPoolPreparedStatements(druidProperties.isPoolPreparedStatements());
        datasource.setMaxPoolPreparedStatementPerConnectionSize(datasource.getMaxPoolPreparedStatementPerConnectionSize());
        datasource.setConnectionProperties(druidProperties.getConnectionProperties());
//        datasource.setFilters("stat,wall,slf4j");
        return datasource;
    }


    @Bean
    public DataSource dataSource (@Autowired DruidDataSource dataSourceOne,
                                  @Autowired DruidDataSource dataSourceTwo) throws Exception {
        ShardingRuleConfiguration shardJdbcConfig = new ShardingRuleConfiguration();
        shardJdbcConfig.getTableRuleConfigs().add(getTableRule());
        shardJdbcConfig.setDefaultDataSourceName("ds_1");
        Map<String,DataSource> dataMap = new LinkedHashMap<>() ;
        dataMap.put("ds_1",dataSourceOne) ;
        dataMap.put("ds_2",dataSourceTwo) ;
        Properties prop = new Properties();
        return ShardingDataSourceFactory.createDataSource(dataMap, shardJdbcConfig, new HashMap<>(), prop);
    }

    /**
     * 分表规则配置
     */
    private static TableRuleConfiguration getTableRule() {
        // 配置表table_one的负责
        TableRuleConfiguration result = new TableRuleConfiguration();
        result.setLogicTable("data_day");
        result.setActualDataNodes("ds_${1..2}.data_day_${1..12}");
        // 配置分库 + 分表策略
        // 根据phone取模分库
        result.setDatabaseShardingStrategyConfig(new StandardShardingStrategyConfiguration("collected_time", new DataSourcePreciseShardingAlgorithm(),new DataSourceRangeShardingAlgorithm()));
        // 根据phone取模分表
        result.setTableShardingStrategyConfig(new StandardShardingStrategyConfiguration("collected_time", new TablePreciseShardingAlgorithm(),new TableRangeShardingAlgorithm()));
        return result;
    }

    /**
     * 2、根据数据源创建SqlSessionFactory
     * @throws Exception
     */
    @Bean(name="sessionFactory")
    public SqlSessionFactoryBean sqlSessionFactoryBean(@Autowired DataSource dataSource){
        SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();
        sessionFactoryBean.setDataSource(dataSource);
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        //此处设置为了解决找不到mapper文件的问题
        String property = environment.getProperty("mybatis.mapperLocations");
        try {
            Resource[] resources = resolver.getResources(property);
            sessionFactoryBean.setMapperLocations(resources);
        } catch (Exception e) {
            log.info("mapper.xml配置信息警告:{}",e.getMessage());
        }
        sessionFactoryBean.setTypeAliasesPackage("com.example.sharingjdbc4digiwin.entity");
        org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
        configuration.setMapUnderscoreToCamelCase(true);
        sessionFactoryBean.setConfiguration(configuration);
        return sessionFactoryBean;
    }
}
